package com.suyang.syt.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.suyang.syt.model.User;
import com.suyang.syt.model.dto.AjaxObj;
import com.suyang.syt.model.dto.UserDTO;
import com.suyang.syt.service.interfaces.UserService;
import com.suyang.syt.util.StringUtil;

@Controller
@RequestMapping("/app")
public class AppRegistController {
	@Autowired
	private UserService userService;

	@RequestMapping(value = "/regist", method = RequestMethod.POST)
	@ResponseBody
	public AjaxObj registCheckCode(HttpServletRequest request, String phone, String checkCode) {
		try {
			HttpSession session = request.getSession();
			String smsCheckCode = (String) session.getAttribute("smsCheckCode");
			long smsCheckTime = (Long) session.getAttribute("smsCheckTime");
			String smsCheckPhone = (String) session.getAttribute("smsCheckPhone");
			if (!smsCheckPhone.equals(phone)) {
				return new AjaxObj(0, "与验证手机号不一致！");
			}
			if (smsCheckTime < System.currentTimeMillis()) {
				return new AjaxObj(0, "验证码已过期!");
			}
			if (!smsCheckCode.equals(checkCode)) {
				return new AjaxObj(0, "验证码不正确!");
			}
			User user = new User();
			user.setUsername(phone);
			user.setPassword("");
			userService.add(new UserDTO(user));
			return new AjaxObj(1, "注册成功");
		} catch (Exception e) {
			return new AjaxObj(0, StringUtil.ERROR_MSG);
		}
	}

}
